<!--
 * @Description: 淘汰管理
-->
<template>
  <BaseMainSlot>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="29"
        :add-active="addActive"
        :del-active="delActive"
        :cancel-active="cancelActive"
        :has-save="false"
        :has-edit="false"
        :has-edit-column="true"
        @showColumn="showColumn"
        @add="add"
        @cancel="cancel"
        @del="del"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading" :listData="tableData"
        @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row, item }">
          <template v-if="!row.index">
            <el-button
              v-if="judgePermission(29, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edits(row)"
            >
              <i class="el-icon-edit-outline"></i> 修 改
            </el-button>
            <el-button
              v-if="judgePermission(29, 'del')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="delmessage(row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </template>
        <template v-slot:facilities="{ row }">
          <template v-if="!row.index">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="checkFacility(row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText + farmingTypeTitles + '记录'"
        :visible.sync="dialogFormVisible"
        width="55%"
        @close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            label="批次名称: "
            prop="batchNo"
            class="w50p"
          >
            <el-select
              v-model="formData.batchNo"
              clearable
              filterable
              @change="changeBatch"
            >
              <el-option
                v-for="(item, index) in batchList"
                :key="index"
                :label="item.batchName"
                :value="item.batchNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="种植设施:" class="w50p" prop="facilityNoArrays">
            <el-select
              v-model="formData.facilityNoArrays"
              multiple
              collapse-tags
              filterable
              clearable
            >
              <el-option
                v-for="item in facilityList"
                :key="item.facilityNo"
                :label="item.facilityName"
                :value="item.facilityNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="淘汰编号:"
            prop="batchSingleNoArrays"
            class="w50p"
          >
            <el-select
              v-model="formData.batchSingleNoArrays"
              multiple
              collapse-tags
              clearable
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in idList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="淘汰原因:"
            prop="cause"
            class="w50p"
          >
            <el-input
              v-model="formData.cause"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="处理人:"
            prop="disposeManNo"
            class="w50p"
          >
            <el-select v-model="formData.disposeManNo" clearable>
              <el-option
                v-for="(item, index) in staffList"
                :key="index.personNo"
                :label="item.person.name"
                :value="item.personNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="淘汰日期："
            prop="eliminateDate"
            class="w50p"
          >
            <el-date-picker
              v-model="formData.eliminateDate"
              type="datetime"
              clearable
            />
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            class="zh-button-one"
            @click="cancel"
          >取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save"
          >确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="设施列表" :visible="facilityDialogVisible"
        class="dialogRec" :before-close="()=>{facilityDialogVisible = false}">
        <div class="facility-list">
          <div v-for="(item,index) in batchFacilityMapperList" :key="index" class="facility-item">
            <div class="info-line">
              <div class="name">设施编号：</div><div class="value">{{ item.facilityNo }}</div>
            </div>
            <div class="info-line">
              <div class="name">设施名称：</div><div class="value">{{ item.facilityName }}</div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="facilityDialogVisible = false">
            关 闭
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :tableColumn="allTableColumn"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogTableColumnVisible = false">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="saveColumn"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Table from '@/components/table/table.vue';
import Pagination from "@/components/Pagination";
import eliminationApi from "@/api/digital-production/health-management/elimination-management/index";
import API from "@/api/digital-production/health-management/pest-follow-up/index";

import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
import nowstaff from "@/api/digital-operation/personnel-cost-mansge/staff-manage/index";
import userreq from "@/api/user/index";

import { mymixin } from "@/utils/mixin";
import { farmingTypeTitle } from "@/utils/validate";
import { mapGetters } from "vuex";

export default {
  name: "ProductionBatchQuery",
  components: {
    SearchForm,
    ActionBar,
    Table,
    Pagination,
    BaseMainSlot,
  },
  mixins: [mymixin],
  data() {
    return {
      tableColumn: [
        { prop: 'batchName', label: '批次名称', minWidth: '200' },
        { prop: 'batchNo', label: '批次号', minWidth: '150' },
        { prop: 'facilityBOs', label: '所在设施', slotName: 'facilities', minWidth: '110' },
        { prop: 'batchSingleNos', label: '淘汰编号', minWidth: '110' },
        { prop: 'cause', label: '淘汰原因', minWidth: '110' },
        { prop: 'disposeManName', label: '处理人', minWidth: '110' },
        { prop: 'eliminateDate', label: '淘汰日期', minWidth: '110' },
        { prop: 'operation', label: '操作', slotName: 'operation', minWidth: '110' },
      ],
      formConfig: [
        {
          label: '批次名称',
          prop: 'batchNo',
          type: 'select',
          options: [], // batchList
          optionKey: { label: 'batchName', value: 'batchNo' },
        }, {
          label: '批次号',
          prop: 'batchNo',
          type: 'select',
          options: [], // batchList
          optionKey: { label: 'batchNo', value: 'batchNo' },
        // }, {
        //   label: '病虫害类别',
        //   prop: 'alarmType',
        //   type: 'select',
        //   options: [
        //     { label: '病害' },
        //     { label: '虫害' },
        //   ],
        //   optionKey: { label: 'name', value: 'value' }
        }, {
          label: '记录日期',
          prop: 'date',
          type: 'daterange',
        },
      ],
      searchlist: {},
      farmingTypeTitles: farmingTypeTitle(),
      // 异常原因
      alarmTypeList: [
        { name: "病害", value: 0 },
        { name: "虫害", value: 1 }
      ],
      alarmTypeLists: [{ name: "病害", value: 0 }],
      // 当前表格选择的数组
      nowSelectList: [],
      // 下拉框数据
      facilityList: [],
      batchList: [],
      staffList: [],
      idList: [],
      batchFacilityMapperList: [],
      facilityDialogVisible: false,
    };
  },
  watch: {},
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  created() {
    // this.setOptions(this.formConfig, 'alarmType', this.farmingTypeTitles == '病害' ? this.alarmTypeLists : this.alarmTypeList)
    this.search();
  },
  mounted() {
    this.getselectdatalist();
  },
  methods: {
    checkFacility(row) {
      this.batchFacilityMapperList = row.facilityBOs || [];
      this.facilityDialogVisible = true;
    },
    // 选择设施
    async changeFacilityNo(e) {
      this.batchList = [];
      this.formData.alarmBatchNo = '';
      let params = {
        no: e.join(','),
        batchStatus: 0,
      };
      let res = await managementtwo.findByFacilityNos(params);
      this.batchList = res.data;
    },
    async changeBatch(e) {
      let res = await API.queryFacility(e);
      this.facilityList = res.data;
      let result = await API.queryIdList(e);
      this.idList = result.data.singleNoList;
    },
    // 获取下拉框数据
    async getselectdatalist() {
      nowstaff.getStaffListByCondition().then((res) => {
        this.staffList = res.data;
      });
      let params = {};
      if (this.nowChanceStau === "add") {
        params = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(","),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
        };
      } else {
        params = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(",")
            .concat([sessionStorage.parentId || ""]),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
        };
      }
      // 获取设施选择框数据
      userreq.getfacilityAll(params).then((res) => {
        this.facilityList = res.data;
      });
      // 获取所有批次
      API.getAllBatchList({ batchType: "SINGLE" }).then((res) => {
        this.batchList = res.data;
        this.formConfig[0].options = res.data;
        this.formConfig[1].options = res.data;
      });
    },
    // 表格查询
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          ...this.searchlist,
          startTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          endTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
        }
      };
      delete params.entity.date
      this.entity = params.entity
      eliminationApi.queryPageList(params).then(res => {
        this.loading = false;
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error("查询失败");
        }
        let data = res.data.content;
        this.tableData = data;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        this.addblankmet();
        this.resetActionBar();
      });
      // 判断搜索输入框数据
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleEdit(row) {
      if (row.id) {
        this.formData = row;
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
        this.canInput = false;
      }
    },
    handleSelectionChange(list) {
      this.nowSelectList = [];
      this.nowSelectList = list.map(item => item.batchEliminateId);
      if (this.nowSelectList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    edits(e) {
      this.formData = { ...e };
      this.nowChanceStau = "edit";
      this.titleText = "修改";
      this.dialogFormVisible = true;
      this.canInput = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
    },
    // 删除时触发方法
    delmessage(e) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      }).then(() => {
        let list = e ? e.batchEliminateId : this.nowSelectList.join(',')
        eliminationApi.delList(list).then(res => {
          if (res.code === 1) {
            this.$message.success("删除成功");
            this.getTableDataList();
          } else {
            this.$message.error("删除失败");
          }
        });
      }).catch(() => {
        this.$message("取消删除");
      });
    },
    save(formData) {
      this.$refs["formData"].validate(valid => {
        if (valid) {
          this.formData.eliminateDate = this.formData.eliminateDate && this.dateToFormat(this.formData.eliminateDate)
          if (this.nowChanceStau === "edit") {
            eliminationApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.search();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            eliminationApi.add({ ...this.formData }).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.search();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.facility-list {
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  flex-wrap: wrap;
  .facility-item {
    width: 400px;
    max-width: 30%;
    min-width: 30%;
    margin-right: 3%;
    margin-bottom: 10px;
    // height: 80px;
    border-radius: 5px;
    // border: 1px solid #ccc;
    box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.15);
    padding: 10px 20px;

    .info-line {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      font-size: 14px;
      &:not(:last-child) {
        margin-bottom: 10px;
      }
      .name {
        text-align: left;
        width: 80px;
        flex-shrink: 0;
      }
      .value {
        width: 100%;
        text-align: left;
        font-weight: normal;
      }
    }
  }
}
::v-deep .tab-select {
  width: 100%;
  .butt-list-sty {
    position: absolute;
    left: 5px;
    top: 7px;
  }
}
</style>
